﻿/*************************************************
作者: Plane
邮箱: 1785275942@qq.com
功能: 编辑器模式下显示组合UI效果

           ~~获取更多教学资讯~~
//----------------*----------------\\
        教学官网：www.qiqiker.com
        官方微信服务号: qiqikertuts
        Plane老师微信: PlaneZhong
\\----------------*----------------//
*************************************************/

using UnityEditor;
using UnityEngine;

[CustomEditor(typeof(WindowRoot), true)]
public class WindowRootInspector : Editor {
    void OnEnable() {
        WindowRoot root = (WindowRoot)target;
        if (root == null || root.windowLayer == WindowLayer.None || !root.EnableCompShow || Application.isPlaying || !root.gameObject.activeSelf) {
            return;
        }
        Transform transform = root.transform;

        for (int i = 0; i < transform.childCount; i++) {
            Transform t = transform.GetChild(i);
            if (t.name.EndsWith("Comp")) {
                GameObject go;
                if (t.childCount == 0) {
                    string path = $"Assets/Resources/{PathDefine.CompPath}{t.name}.prefab";
                    GameObject obj = AssetDatabase.LoadAssetAtPath<GameObject>(path);
                    go = PrefabUtility.InstantiatePrefab(obj) as GameObject;
                    go.transform.SetParent(t);
                    go.transform.localPosition = Vector3.zero;
                    go.transform.localScale = Vector3.one;
                }
            }
        }
    }

    private void OnDisable() {
        WindowRoot root = (WindowRoot)target;
        if (root == null || root.windowLayer == WindowLayer.None || !root.EnableCompShow || Application.isPlaying || !root.gameObject.activeSelf) {
            return;
        }
        Transform transform = root.transform;

        GameObject selObj = Selection.activeObject as GameObject;
        bool isSelectChild = false;
        while (selObj != null && selObj.transform.parent != null) {
            if (selObj.transform.parent.name == root.name) {
                isSelectChild = true;
                break;
            }
            else {
                selObj = selObj.transform.parent.gameObject;
            }
        }

        if (!isSelectChild) {
            for (int i = 0; i < transform.childCount; i++) {
                Transform t = transform.GetChild(i);
                if (t.name.EndsWith("Comp") && t.childCount > 0) {
                    Transform trans = t.GetChild(0);
                    if (trans != null) {
                        DestroyImmediate(trans.gameObject);
                    }
                }
            }
        }
    }
}